<template>
  <div class="teacher-title-apply-container">
    <h2>{{ getPageTitle() }}</h2>
    
    <el-tabs v-model="activeTab">
      <el-tab-pane label="申请职称" name="apply">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>教师职称申请表</span>
            </div>
          </template>
          
          <el-form :model="titleForm" :rules="rules" ref="titleForm" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="当前职称" prop="currentTitle">
                  <el-input v-model="titleForm.currentTitle" disabled></el-input>
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="申请职称" prop="appliedTitle">
                  <el-select v-model="titleForm.appliedTitle" placeholder="请选择申请职称" style="width: 100%">
                    <el-option label="讲师" value="讲师"></el-option>
                    <el-option label="副教授" value="副教授"></el-option>
                    <el-option label="教授" value="教授"></el-option>
                    <el-option label="研究员" value="研究员"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              
              <el-col :span="24">
                <el-form-item label="资格描述" prop="qualificationDesc">
                  <el-input 
                    v-model="titleForm.qualificationDesc" 
                    type="textarea" 
                    :rows="4" 
                    placeholder="请详细说明您的资格条件，包括学历、工作年限、教学经验等">
                  </el-input>
                </el-form-item>
              </el-col>
              
              <el-col :span="24">
                <el-form-item label="主要成就" prop="achievements">
                  <el-input 
                    v-model="titleForm.achievements" 
                    type="textarea" 
                    :rows="4" 
                    placeholder="请说明您的主要成就，包括科研成果、论文发表、项目经验、获奖情况等">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="证明材料">
              <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                action="/api/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="5"
                :on-exceed="handleExceed"
                multiple>
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持jpg/png/pdf/doc等格式，单个文件不超过10MB，最多上传5个文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="submitApplication">提交申请</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="申请记录" name="records">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>我的申请记录</span>
              <el-button @click="refreshRecords">刷新</el-button>
            </div>
          </template>
          
          <el-table :data="myApplications" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="申请编号" width="120"></el-table-column>
            <el-table-column prop="currentTitle" label="当前职称" width="120"></el-table-column>
            <el-table-column prop="appliedTitle" label="申请职称" width="120"></el-table-column>
            <el-table-column prop="applyDate" label="申请日期" width="180"></el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="viewDetail(scope.row)">详情</el-button>
                <el-button 
                  v-if="scope.row.status === '待提交'" 
                  size="small" 
                  type="danger" 
                  @click="cancelApplication(scope.row)">
                  撤销
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            @current-change="handlePageChange"
            class="pagination">
          </el-pagination>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane v-if="userRole === 'principal'" label="待审批" name="pending">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>待审批职称申请</span>
              <el-button @click="refreshRecords">刷新</el-button>
            </div>
          </template>
          
          <el-table :data="pendingApplications" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="申请编号" width="120"></el-table-column>
            <el-table-column prop="teacherName" label="申请人" width="120"></el-table-column>
            <el-table-column prop="currentTitle" label="当前职称" width="120"></el-table-column>
            <el-table-column prop="appliedTitle" label="申请职称" width="120"></el-table-column>
            <el-table-column prop="applyDate" label="申请日期" width="180"></el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="viewDetail(scope.row)">详情</el-button>
                <el-button size="small" type="primary" @click="approveApplication(scope.row, 'approved')">批准</el-button>
                <el-button size="small" type="danger" @click="approveApplication(scope.row, 'rejected')">拒绝</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            @current-change="handlePageChange"
            class="pagination">
          </el-pagination>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 申请详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="申请详情" width="60%">
      <el-form :model="selectedApplication" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请编号:">
              <span>{{ selectedApplication.id }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人:">
              <span>{{ selectedApplication.teacherName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前职称:">
              <span>{{ selectedApplication.currentTitle }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请职称:">
              <span>{{ selectedApplication.appliedTitle }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请日期:">
              <span>{{ selectedApplication.applyDate }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态:">
              <el-tag :type="getStatusType(selectedApplication.status)">
                {{ selectedApplication.status }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="资格描述:">
          <el-input 
            v-model="selectedApplication.qualificationDesc" 
            type="textarea" 
            :rows="3" 
            disabled>
          </el-input>
        </el-form-item>
        
        <el-form-item label="主要成就:">
          <el-input 
            v-model="selectedApplication.achievements" 
            type="textarea" 
            :rows="3" 
            disabled>
          </el-input>
        </el-form-item>
        
        <el-form-item label="证明材料:">
          <div v-if="selectedApplication.materials && selectedApplication.materials.length > 0">
            <el-card v-for="(material, index) in selectedApplication.materials" :key="index" class="material-card">
              <div class="material-item">
                <el-icon><Document /></el-icon>
                <span class="material-name">{{ material.name }}</span>
                <el-button size="small" @click="downloadMaterial(material)">下载</el-button>
              </div>
            </el-card>
          </div>
          <div v-else>
            <el-empty description="暂无证明材料" />
          </div>
        </el-form-item>
        
        <el-form-item v-if="selectedApplication.reviewComment" label="审批意见:">
          <el-input 
            v-model="selectedApplication.reviewComment" 
            type="textarea" 
            :rows="2" 
            disabled>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'TeacherTitleApply',
  setup() {
    const activeTab = ref('apply')
    const userRole = ref('teacher') // teacher or principal
    const detailDialogVisible = ref(false)
    const loading = ref(false)
    const total = ref(0)
    const pageSize = ref(10)
    const fileList = ref([])
    const myApplications = ref([])
    const pendingApplications = ref([])
    const selectedApplication = ref({})
    
    const titleForm = reactive({
      currentTitle: '助理教授',
      appliedTitle: '',
      qualificationDesc: '',
      achievements: ''
    })
    
    const rules = {
      appliedTitle: [
        { required: true, message: '请选择申请职称', trigger: 'change' }
      ],
      qualificationDesc: [
        { required: true, message: '请输入资格描述', trigger: 'blur' }
      ],
      achievements: [
        { required: true, message: '请输入主要成就', trigger: 'blur' }
      ]
    }
    
    const getPageTitle = () => {
      return userRole.value === 'principal' ? '教师职称管理' : '职称申请'
    }
    
    const getStatusType = (status) => {
      const statusMap = {
        '待提交': 'info',
        '待审批': 'warning',
        '已批准': 'success',
        '已拒绝': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    const submitApplication = () => {
      ElMessage.success('申请提交成功，请等待审批！')
    }
    
    const resetForm = () => {
      titleForm.appliedTitle = ''
      titleForm.qualificationDesc = ''
      titleForm.achievements = ''
      fileList.value = []
    }
    
    const refreshRecords = () => {
      loading.value = true
      // 模拟刷新数据
      setTimeout(() => {
        loading.value = false
        ElMessage.success('刷新成功')
      }, 500)
    }
    
    const viewDetail = (row) => {
      selectedApplication.value = row
      detailDialogVisible.value = true
    }
    
    const approveApplication = (row, decision) => {
      ElMessageBox.prompt(`请输入${decision === 'approved' ? '批准' : '拒绝'}意见：`, '审批意见', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '意见不能为空'
      }).then(({ value }) => {
        ElMessage.success(`${decision === 'approved' ? '批准' : '拒绝'}成功`)
        refreshRecords()
      }).catch(() => {
        ElMessage.info('取消操作')
      })
    }
    
    const cancelApplication = (row) => {
      ElMessageBox.confirm('确定要撤销此申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessage.success('申请已撤销')
        refreshRecords()
      }).catch(() => {
        ElMessage.info('已取消')
      })
    }
    
    const handlePageChange = (page) => {
      // 处理分页变化
    }
    
    const handlePreview = (file) => {
      console.log(file)
    }
    
    const handleRemove = (file, fileList) => {
      console.log(file, fileList)
    }
    
    const beforeRemove = (uploadFile, uploadFiles) => {
      return ElMessageBox.confirm(`确定移除 ${uploadFile.name}？`)
    }
    
    const handleExceed = (files, fileList) => {
      ElMessage.warning('最多只能上传5个文件')
    }
    
    const downloadMaterial = (material) => {
      ElMessage.info(`下载文件: ${material.name}`)
    }
    
    onMounted(() => {
      // 初始化数据
      myApplications.value = [
        {
          id: 1,
          teacherName: '张老师',
          currentTitle: '助理教授',
          appliedTitle: '副教授',
          applyDate: '2025-10-20',
          status: '待审批',
          qualificationDesc: '博士学历，任教5年，主讲《高等数学》等课程',
          achievements: '发表SCI论文3篇，主持省级项目1项',
          materials: [
            { name: '学历证明.pdf' },
            { name: '论文清单.docx' }
          ]
        }
      ]
      
      pendingApplications.value = [
        {
          id: 1,
          teacherName: '张老师',
          currentTitle: '助理教授',
          appliedTitle: '副教授',
          applyDate: '2025-10-20',
          status: '待审批',
          qualificationDesc: '博士学历，任教5年，主讲《高等数学》等课程',
          achievements: '发表SCI论文3篇，主持省级项目1项',
          materials: [
            { name: '学历证明.pdf' },
            { name: '论文清单.docx' }
          ]
        },
        {
          id: 2,
          teacherName: '李老师',
          currentTitle: '讲师',
          appliedTitle: '副教授',
          applyDate: '2025-10-18',
          status: '待审批',
          qualificationDesc: '硕士学历，任教8年，主讲《大学物理》等课程',
          achievements: '发表核心期刊论文5篇，参与国家级项目2项',
          materials: [
            { name: '学历证明.pdf' },
            { name: '项目证明.docx' }
          ]
        }
      ]
    })
    
    return {
      activeTab,
      userRole,
      detailDialogVisible,
      loading,
      total,
      pageSize,
      fileList,
      myApplications,
      pendingApplications,
      selectedApplication,
      titleForm,
      rules,
      getPageTitle,
      getStatusType,
      submitApplication,
      resetForm,
      refreshRecords,
      viewDetail,
      approveApplication,
      cancelApplication,
      handlePageChange,
      handlePreview,
      handleRemove,
      beforeRemove,
      handleExceed,
      downloadMaterial
    }
  }
}
</script>

<style scoped>
.teacher-title-apply-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.material-card {
  margin-bottom: 10px;
}

.material-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.material-name {
  flex: 1;
  margin: 0 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>